package com.onlineOrder.webAction;

import com.onlineOrder.bean.indentList;
import com.onlineOrder.bean.shopList;
import com.onlineOrder.bean.userList;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@WebServlet({"/adminShopList", "/adminUserList", "/adminShopDetail", "/adminShopDelete", "/adminShopRegister", "/adminShopManage", "/adminUserRegister","/adminIndentList"})
public class adminServlet extends HttpServlet {
    public static String shopID = "";

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String servletPath = request.getServletPath();
        if ("/adminShopList".equals(servletPath)) {
            doAdminShopList(request, response);
        } else if ("/adminUserList".equals(servletPath)) {
            doAdminUserList(request, response);
        } else if ("/adminShopDetail".equals(servletPath)) {
            doAdminShopDetail(request, response);
        } else if ("/adminShopDelete".equals(servletPath)) {
            doAdminShopDelete(request, response);
        } else if ("/adminShopRegister".equals(servletPath)) {
            doAdminShopRegister(request, response);
        } else if ("/adminShopManage".equals(servletPath)) {
            doAdminShopManage(request, response);
        } else if ("/adminUserRegister".equals(servletPath)) {
            doAdminUserRegister(request, response);
        }else if ("/adminIndentList".equals(servletPath)) {
            doAdminIndentList(request, response);
        }

    }

    private void doAdminIndentList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        List<indentList> buyLists = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder","root","123456");
            String sql="select menus,amount,shopName,phone,time,state,userId,userName,shopId from indent ";
            ps=conn.prepareStatement(sql);

            rs=ps.executeQuery();
            while (rs.next()){
                indentList indentList = new indentList();

                indentList.setMenus(rs.getString("menus"));
                indentList.setAmount(rs.getString("amount"));
                indentList.setShopName(rs.getString("shopName"));
                indentList.setPhone(rs.getString("phone"));
                indentList.setTime(rs.getString("time"));
                indentList.setUserId(rs.getString("userId"));
                indentList.setUserName(rs.getString("userName"));
                indentList.setShopId(rs.getString("shopId"));
                indentList.setState(rs.getString("state"));

                buyLists.add(indentList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将一个集合放到请求域当中
        request.setAttribute("buyLists",buyLists);

        // 转发（不要重定向）
        request.getRequestDispatcher("/adminMenuBuy.jsp").forward(request, response);
    }


    private void doAdminShopManage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String shopID = request.getParameter("shopID");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        int count = 0;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder", "root", "123456");
            String sql = "update shop set register='1',state='正常' where id=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, shopID);
            count = ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }

        String contextPath = request.getContextPath();
        if (count == 1) {
            //更新成功
            // 重定向
            response.sendRedirect(contextPath + "/adminShopList");
        } else {
            //更新失败
            response.sendRedirect("tem.jsp");
        }
    }

    private void doAdminShopRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");

        String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
        String date2 = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
        date = date.substring(2, 4) + date.substring(5, 7) + date.substring(8);
        date2 = date2.substring(0, 2) + date2.substring(3, 5) + date2.substring(6);
        shopID = (date + date2).substring(3, 11);

        String shopName = request.getParameter("shopName");
        String shopPwd = request.getParameter("shopPwd");
        String shopOwner = request.getParameter("shopOwner");
        String shopPhone = request.getParameter("shopPhone");
        String shopMessage = request.getParameter("shopMessage");
        String shopAddress = request.getParameter("shopAddress");
        String shopState = "审核中";
        String shopSale = "0";        //总营收
        String shopReg = "0";         //注册状态，0表示待审核
        String flag = "2";            //身份标识，2为商家

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        int count = 0;


        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder?serverTimezone=UTC&characterEncoding=utf-8", "root", "123456");
            String sql = "insert into shop values(?,?,?,?,?,?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, shopID);
            ps.setString(2, shopName);
            ps.setString(3, shopSale);
            ps.setString(4, shopPwd);
            ps.setString(5, shopOwner);
            ps.setString(6, shopPhone);
            ps.setString(7, shopMessage);
            ps.setString(8, shopAddress);
            ps.setString(9, shopState);
            ps.setString(10, shopReg);
            ps.setString(11, flag);

            count = ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (count == 1) {
            response.sendRedirect(request.getContextPath() + "/tem.jsp");
        }

    }

    private void doAdminShopDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String shopID = request.getParameter("shopID");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        shopList shopList = new shopList();

        int count = 0;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder", "root", "123456");
            String sql = "delete from shop where id=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, shopID);
            count = ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }

        String contextPath = request.getContextPath();
        if (count == 1) {
            //更新成功
            // 重定向
            response.sendRedirect(contextPath + "/adminShopList");
        } else {
            //更新失败
            response.sendRedirect("tem.jsp");
        }
    }

    private void doAdminShopDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取部门信息
        String shopID = request.getParameter("shopID");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        shopList shopList = new shopList();

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder", "root", "123456");
            String sql = "select id,shopName,sale,Pwd,name,phone,message,address,state,register,flag from shop where id=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, shopID);
            rs = ps.executeQuery();

            if (rs.next()) {

                shopList.setShopId(rs.getString("id"));
                shopList.setShopName(rs.getString("shopName"));
                shopList.setSale(rs.getString("sale"));
                shopList.setPassword(rs.getString("Pwd"));
                shopList.setOwner(rs.getString("name"));
                shopList.setPhone(rs.getString("phone"));
                shopList.setMessage(rs.getString("message"));
                shopList.setAddress(rs.getString("address"));
                shopList.setState(rs.getString("state"));
                shopList.setRegister(rs.getString("register"));
                shopList.setFlag(rs.getString("flag"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//         将一个集合放到请求域当中
        request.setAttribute("shopList", shopList);

//         转发（不要重定向）
        request.getRequestDispatcher("/shopDetail.jsp").forward(request, response);
    }

    private void doAdminShopList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        List<shopList> shopLists = new ArrayList<>();

        //连接数据库
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;


        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder", "root", "123456");
            String sql = "select id,shopName,sale,name,phone,message,address,state,register from shop";

            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                shopList shopList = new shopList();

                shopList.setShopId(rs.getString("id"));
                shopList.setShopName(rs.getString("shopName"));
                shopList.setSale(rs.getString("sale"));
                shopList.setOwner(rs.getString("name"));
                shopList.setPhone(rs.getString("phone"));
                shopList.setMessage(rs.getString("message"));
                shopList.setAddress(rs.getString("address"));
                shopList.setState(rs.getString("state"));
                shopList.setRegister(rs.getString("register"));

                shopLists.add(shopList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将一个集合放到请求域当中
        request.setAttribute("shopList", shopLists);

        // 转发（不要重定向）
        request.getRequestDispatcher("/shopList.jsp").forward(request, response);
    }

    private void doAdminUserList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<userList> userLists = new ArrayList<>();

        //连接数据库
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder", "root", "123456");
            String sql = "select id,userName,Pwd,name,phone,sex,address from user";

            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                userList userList = new userList();

                userList.setUserId(rs.getString("id"));
                userList.setUserName(rs.getString("userName"));
                userList.setPassword(rs.getString("Pwd"));
                userList.setName(rs.getString("name"));
                userList.setPhone(rs.getString("phone"));
                userList.setSex(rs.getString("sex"));
                userList.setAddress(rs.getString("address"));
//                userList.setState(rs.getString("state"));
//                userList.setRegister(rs.getString("register"));

                userLists.add(userList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将一个集合放到请求域当中
        request.setAttribute("userList", userLists);

        // 转发（不要重定向）
        request.getRequestDispatcher("/userList.jsp").forward(request, response);
    }

    private void doAdminUserRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");

        String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
        String date2 = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
        date = date.substring(2, 4) + date.substring(5, 7) + date.substring(8);
        date2 = date2.substring(0, 2) + date2.substring(3, 5) + date2.substring(6);
        String idDemo = "22" + (date + date2).substring(2, 6) + (date + date2).substring(10, 12);


//        shopID="22301302";

        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String userRName = request.getParameter("userRName");
        String userPhone = request.getParameter("userPhone");
        String userSex = request.getParameter("userMessage");
        String userAddress = request.getParameter("userAddress");

        String flag = "1";            //身份标识，1为用户

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        int count = 0;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder?serverTimezone=UTC&characterEncoding=utf-8", "root", "123456");
            String sql = "insert into user values(?,?,?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, idDemo);
            ps.setString(2, userName);
            ps.setString(3, userPwd);
            ps.setString(4, userRName);
            ps.setString(5, userPhone);
            ps.setString(6, userSex);
            ps.setString(7, userAddress);
            ps.setString(8, flag);

            count = ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        if (count == 1) {
            response.sendRedirect(request.getContextPath() + "/tem.jsp");
        }


    }
}
